package com.szqhyxj.youxiangju.biz.receipt.receiptdetail.signature;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.szqhyxj.youxiangju.BaseActivity;
import com.szqhyxj.youxiangju.R;
import com.szqhyxj.youxiangju.biz.creditReport.CreditReportEntity;
import com.szqhyxj.youxiangju.biz.receipt.fail.ReceiptFailActivity;
import com.szqhyxj.youxiangju.biz.receipt.record.ReceiptRecordActicirty;
import com.szqhyxj.youxiangju.biz.receipt.success.ReceiptSuccessActivity;
import com.szqhyxj.youxiangju.sys.components.NavigationBar;
import com.szqhyxj.youxiangju.sys.components.draw.SignatureView;
import com.szqhyxj.youxiangju.sys.components.view.popview.GainSMSPopView;
import com.szqhyxj.youxiangju.sys.util.PhonenumberUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by leung on 2018/11/4.
 */

public class SignatureActivity extends BaseActivity implements NavigationBar.NavigationBarListener, SignatureContract.View {

    private static CreditReportEntity creditReportEntity;
    @BindView(R.id.navigationBar)
    NavigationBar navigationBar;
    @BindView(R.id.cardNo)
    TextView cardNo;
    @BindView(R.id.amount)
    TextView amount;

    private String creatTime;
    SignaturePresenter presenter;
    private File file;
    private String cardNumber;
    @BindColor(R.color.policytext)
    int color66;
    @BindColor(R.color.invitationColor)
    int invitationColor;
    private String cardPhone;

    public static void start(Activity activity, String cardno, String amount, String cardPhone) {
        Intent intent = new Intent();
        intent.setClass(activity, SignatureActivity.class);
        intent.putExtra("cardno", cardno);
        intent.putExtra("amount", amount);
        intent.putExtra("cardPhone", cardPhone);
        activity.startActivityForResult(intent, 1);


    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signature);
        ButterKnife.bind(this);
        cardNumber = getIntent().getStringExtra("cardno");
        cardNo.setText(PhonenumberUtil.hiddenBankCards(getIntent().getStringExtra("cardno")));
        String stramount = getIntent().getStringExtra("amount");
        BigDecimal bigDecimal = new BigDecimal(stramount);
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        String money = decimalFormat.format(bigDecimal);
        cardPhone = getIntent().getStringExtra("cardPhone");
        amount.setText(money);
        gainPermission();
        gainCurrenTime();
        initView();
        navigationBar.setNavigationBarListener(this);
        presenter = new SignaturePresenter(this);
    }

    private void gainPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ContextCompat.checkSelfPermission(SignatureActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(SignatureActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4);
            } else {
                Toast.makeText(this, "已开启权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void gainCurrenTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        creatTime = formatter.format(curDate);
    }

    GainSMSPopView gainSMSPopView;

    private void initView() {
        final TextView mClearButton = findViewById(R.id.clear);
        final TextView mSaveButton = findViewById(R.id.commit_signature);
        mSaveButton.setBackgroundColor(color66);
        mSaveButton.setEnabled(false);
        final SignatureView mSignaturePad = (SignatureView) findViewById(R.id.signature_pad);
        mSignaturePad.setOnSignedListener(new SignatureView.OnSignedListener() {
            @Override
            public void onSigned() {
                mSaveButton.setEnabled(true);
                mClearButton.setEnabled(true);
                mSaveButton.setBackgroundColor(invitationColor);

            }

            @Override
            public void onClear() {
                mSaveButton.setEnabled(false);
                mClearButton.setEnabled(false);
                mSaveButton.setBackgroundColor(color66);

            }
        });

        mClearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSignaturePad.clear();
            }
        });
        mSaveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
                Bitmap bitmap = compressScale(signatureBitmap);
                if (addSignatureToGallery(bitmap)) {
                    gainSMSPopView = new GainSMSPopView(SignatureActivity.this, cardPhone,"已发送验证码至");
                    gainSMSPopView.setOnClickListener(new GainSMSPopView.OnClickListener() {
                        @Override
                        public void onClickConfirm(String code) {
                            if (code.equals("")){
                                Toast.makeText(SignatureActivity.this,"验证码不能为空！",Toast.LENGTH_LONG).show();
                            }else {
                                presenter.verificationMsg(cardPhone, code);

                            }
                        }

                        @Override
                        public void onClickgetMsg() {
                            presenter.getMsg(cardPhone);
                        }
                    });
                    gainSMSPopView.show();

                } else {
                    Toast.makeText(SignatureActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public boolean addSignatureToGallery(Bitmap signature) {
        boolean result = false;
        try {
            final File photo = new File(getAlbumStorageDir("优享钜手写签名"), String.format(creatTime + ".jpg", System.currentTimeMillis()));
            file = photo;
            Log.e("aaa", photo + "");
            saveBitmapToJPG(signature, photo);
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(photo);
            mediaScanIntent.setData(contentUri);
            SignatureActivity.this.sendBroadcast(mediaScanIntent);
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public File getAlbumStorageDir(String albumName) {
        File file = new File(Environment.getExternalStorageDirectory(), albumName);
        if (!file.mkdirs()) {
            Log.e("SignaturePad", "Directory not created");
        }
        return file;
    }

    public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
    }

    /**
     *  
     *  * 图片按比例大小压缩方法 
     *  * 
     *  * @param image （根据Bitmap图片压缩） 
     *  * @return 
     *  
     */
    public static Bitmap compressScale(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if (baos.toByteArray().length / 1024 > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//降低图片从ARGB888到RGB565
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        // return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
        return bitmap;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 4:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "已打开权限！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "请打开权限！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        super.onResume();
    }

    @Override
    public void navigationLeft() {
        Intent intent = new Intent();
        //把返回数据存入Intent

        //设置返回数据
        this.setResult(RESULT_CANCELED, intent);
        //关闭Activity
        this.finish();
        finish();
    }

    @Override
    public void navigationRight() {

    }

    @Override
    public void showCommitSign() {
        // presenter.signCommit();
    }

    @Override
    public void reportSuccess() {
       // ReceiptSuccessActivity.start(this,true);
        ReceiptRecordActicirty.start(this,"device");
    }

    @Override
    public void showCommitSuccess(String s) {

    }

    @Override
    public void showFile(String s) {
        Toast.makeText(this, s, Toast.LENGTH_LONG).show();
        ReceiptFailActivity.start(this, s);
        finish();
    }

    @Override
    public void showAcquiredVerificationCodeSuccess() {
        Toast.makeText(this, "验证码已发送", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void showAcquiringVerificationCode(int min) {
        gainSMSPopView.setMinute(String.format("%ss", String.valueOf(min)), 2);
    }

    @Override
    public void showAcquiredVerificationCode() {
        gainSMSPopView.setMinute("获取", 1);
    }

    @Override
    public void showAcquiredVerificationCodeFail(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void showVerificationSuccess() {
        gainSMSPopView.dismiss();
        presenter.postSign(cardNumber, amount.getText().toString(), file);
        Toast.makeText(SignatureActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            //把返回数据存入Intent
            //设置返回数据
            this.setResult(RESULT_CANCELED, intent);
            //关闭Activity
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
